//
//  Place.m
//  gong
//
//  Created by echo on 14-1-11.
//  Copyright (c) 2014年 echo. All rights reserved.
//

#import "Place.h"
#import "PositionTools.h"
#import "UICreator.h"
#import "PositionTools.h"
#import "Constants.h"
#import "AutoRemoveMessageView.h"
#import "ScriptParsor.h"
#import "BoxfishAnimator.h"
#import "SimpleAudioEngine.h"
#import "GameManager.h"
#import "TaskManager+IsDone.h"
#import "Player.h"
#import "NPC.h"

@interface Place () <UIGestureRecognizerDelegate>

@end

@implementation Place
{
    UIImageView *_talkBkView;
    UILabel *_talkLabel;
    UIImageView *_bkView;
    
    UILabel *_npcTalkLabel;
    UIButton *_storyButton;
    UIButton *_taskButton;
    UITapGestureRecognizer *_tap;
    
    NSMutableArray *_transitionBkArray;
}

- (void)dealloc
{
    [_containerView removeGestureRecognizer:_tap];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init:(UIView*)container
{
    self = [super init];
    if (self) {
        _containerView = container;
        _needTransition = NO;
        
        _transitionBkArray = [NSMutableArray array];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initTransitionInfo) name:MsgRestartGame object:nil];
        
        [self initDefault];
    }
    
    return self;
}

- (void)initDefault
{
    
}

- (void)initTransitionInfo
{
    
}

- (void)clearTransitionInfo
{
    _transitionImageArray = nil;
}

- (BOOL)canEnter
{
    if ([[[TaskManager sharedInstance] getCurrentTask].triggerPlace isEqualToString:self.name]) {
        return YES;
    } else {
        return [Player sharedInstance].rank >= _rankLimit;
    }
}

- (void)createSmallImage:(CGPoint)position
{
    NSArray *entryImages = @[[UIImage imageNamed:@"butterfly1.png"],
                             [UIImage imageNamed:@"butterfly2.png"],
                             [UIImage imageNamed:@"butterfly3.png"]];
    
    _smallImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 197, 195)];
    _smallImageView.animationImages = entryImages;
    _smallImageView.animationDuration = 0.25;
    _smallImageView.animationRepeatCount = 0;
    [_smallImageView startAnimating];
    
    [self.streetView addSubview:_smallImageView];
    _smallImageView.center = position;
    
    _smallImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
    [_smallImageView addGestureRecognizer:tap];
}

- (void)handleTap
{
    if ([self canEnter]) {
        [BoxfishAnimator pulse:_smallImageView completion:^{
            [self enter];
        }];
    } else {
        [AutoRemoveMessageView show:@"你暂时不能进入此房间。" withContainerView:_containerView completion:nil];
    }
}

- (void)enter
{
    NSLog(@"你进入了%@",self.name);
    [[NSNotificationCenter defaultCenter] postNotificationName:MsgEnterPlace object:nil];

    [GameManager sharedInstance].currentPlaceName = self.name;
    
    if (_needTransition) {
        [self enterWithTransition];
    } else {
        [self directEnter];
    }
}

- (void)directEnter
{
    [GameManager sharedInstance].memory.isInStreet = NO;
    [GameManager sharedInstance].memory.house = _placeClassName;
    [GameManager sharedInstance].memory.houseName = self.name;
    
    if ([[[TaskManager sharedInstance] getCurrentTask].triggerPlace isEqualToString:[GameManager sharedInstance].currentPlaceName]) {
        [[TaskManager sharedInstance] monitorTaskIsDone];
        
        if ([[TaskManager sharedInstance] getCurrentScript]) {
            ScriptParsor *parsor = [[ScriptParsor sharedInstance] init];
            parsor.scriptContainerView = [GameManager sharedInstance].gameMainViewContainer;
            [parsor parse:[[TaskManager sharedInstance] getCurrentScript]];
        }
    } else {
        [self createDefault];
    }
}

- (void)enterWithTransition
{
    if (_transitionImageArray.count > 0) {
        UIImageView *transitionBk = [UICreator createImageViewFromImagename:_transitionImageArray[0]];
        [PositionTools placeView:transitionBk atTheCenterOfTheView:_containerView];
        transitionBk.alpha = 0;
        [_transitionBkArray addObject:transitionBk];
        
        [UIView animateWithDuration:2 animations:^{
            transitionBk.alpha = 1;
        } completion:^(BOOL finished) {
            [_transitionImageArray removeObjectAtIndex:0];
            [self enterWithTransition];
        }];
    } else {
        [self directEnter];
        _bkView.alpha = 0;
        
        [UIView animateWithDuration:2 animations:^{
            _bkView.alpha = 1;
        } completion:^(BOOL finished) {
            for (UIView *view in _transitionBkArray) {
                [view removeFromSuperview];
            }
            [_transitionBkArray removeAllObjects];
        }];
    }
}

- (void)continueStory
{
    [[ScriptParsor sharedInstance] parseOneLine];
}

- (void)createLeaveButton
{
    UIButton *leaveButton = [UICreator createButtonWithNormalImage:@"exit.png"
                                                  highlightedImage:nil
                                                            target:self
                                                            action:@selector(leave)
                                                             use2X:YES];
    [PositionTools placeView:leaveButton atTheLeftTopOfTheView:_bkView offset:CGSizeMake(20, 20)];
}

- (void)createDefault
{
    [self createWithBackground:_bk];
    [self createLeaveButton];
    [self playMusic:_music];
}
    
- (void)create
{
    [self createDefault];
    [self createTalk];
    
    if ([[[TaskManager sharedInstance] getCurrentTask].triggerPlace isEqualToString:[GameManager sharedInstance].currentPlaceName]) {
        if (!_storyButton) {
            _storyButton = [UICreator createButtonWithNormalImage:@"continue.png"
                                                 highlightedImage:nil
                                                           target:self
                                                           action:@selector(continueStory)
                                                            use2X:YES];
            [PositionTools placeView:_storyButton atTheRightTopOfTheView:_bkView offset:CGSizeMake(100, 20)];
        }
        
        if (!_taskButton) {
            _taskButton = [UICreator createButtonWithNormalImage:@"tasknote.png" highlightedImage:nil target:self action:@selector(showTask) use2X:YES];
            [PositionTools placeView:_taskButton atTheLeftBottomOfTheView:_bkView offset:CGSizeMake(20, 20)];
        }
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeTalkToTop) name:MsgShowNPC object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNPCTalk:) name:MsgNPCTalk object:nil];
}

- (void)showTask
{
    NSString *taskDescription = [[TaskManager sharedInstance] getCurrentTask].description;
    [[[UIAlertView alloc] initWithTitle:@"当前任务" message:taskDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}

- (void)createTalk
{
    _talkBkView = [UICreator createImageViewFromImagename:@"dialogBk.jpg"];
    [PositionTools placeView:_talkBkView atTheBottomMiddleOfTheView:_containerView offset:0];
    
    _talkLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _containerView.frame.size.width - 200, 90)];
    _talkLabel.backgroundColor = [UIColor clearColor];
    _talkLabel.textColor = [UIColor blackColor];
    _talkLabel.font = [UIFont systemFontOfSize:20];
    _talkLabel.numberOfLines = 0;
    _talkLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [PositionTools placeView:_talkLabel atTheLeftMiddleOfTheView:_talkBkView offset:160];
}

- (void)makeTalkToTop
{
    [_containerView bringSubviewToFront:_talkBkView];
}

- (void)handleNPCTalk:(NSNotification*)notification
{
    if (![self isEqual:[notification object]]) {
        _talkBkView.alpha = 0;        
    }
}

- (void)createWithBackground:(NSString*)bk
{
    _bkView = [[UIImageView alloc] initWithImage:[UICreator getCircumscribedImage:[UIImage imageNamed:bk] withSize:CGSizeMake(1024, 768)]];
    [PositionTools placeView:_bkView atTheCenterOfTheView:_containerView];
    
    _bkView.userInteractionEnabled = YES;
    
    UIButton *saveButton = [UICreator createButtonWithNormalImage:@"save.png" highlightedImage:nil target:[GameManager sharedInstance] action:@selector(save) use2X:YES];
    [PositionTools placeView:saveButton atTheRightTopOfTheView:_containerView offset:CGSizeMake(20, 20)];
    
    _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePlaceTap:)];
    [_containerView addGestureRecognizer:_tap];
    _tap.delegate = self;
}

- (void)handlePlaceTap:(UIGestureRecognizer*)gesture
{
//    [[ScriptParsor sharedInstance] parseOneLine];
}

- (void)playMusic:(NSString *)music
{
    if (music) {
        [[SimpleAudioEngine sharedEngine] playBackgroundMusic:_music loop:YES];
    }
}

- (void)stopMusic
{
    [[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
}
    
- (void)showTalk:(NSString *)talk npc:(NPC*)npc
{
    if (_npcTalkLabel) {
        [_npcTalkLabel removeFromSuperview];
    }
    
    if (npc) {
        _talkBkView.alpha = 0;
        _npcTalkLabel = [UICreator createLabel:talk
                               constrainedSize:CGSizeMake(300, CGFLOAT_MAX)
                                         color:[UIColor blackColor]
                                          font:[UIFont systemFontOfSize:30]];
        _npcTalkLabel.backgroundColor = [UIColor whiteColor];
        
        [_containerView addSubview:_npcTalkLabel];
        
        float x;
        if (ShowInTheMiddle == npc.showPosition) {
            x = 0.75 * _containerView.frame.size.width;
        } else if (ShowAtTheLeft == npc.showPosition) {
            x = 0.45 * _containerView.frame.size.width;
        } else if (ShowAtTheRight == npc.showPosition) {
            x = 0.55 * _containerView.frame.size.width;
        } else if (ShowAtTheLeft1 == npc.showPosition) {
            x = 0.45 * _containerView.frame.size.width;
        } else if (ShowAtTheLeft2 == npc.showPosition) {
            x = 0.35 * _containerView.frame.size.width;
        } else if (ShowAtTheRight1 == npc.showPosition) {
            x = 0.55 * _containerView.frame.size.width;
        } else if (ShowAtTheRight2 == npc.showPosition) {
            x = 0.85 * _containerView.frame.size.width;
        } else {
            x = 0.5 * _containerView.frame.size.width;
        }
        
        float y = 100 + _npcTalkLabel.frame.size.height / 2;
        
        _npcTalkLabel.center = CGPointMake(x, y);
        
    } else {
        _talkBkView.alpha = 1;
        _talkLabel.text = talk;
        [[NSNotificationCenter defaultCenter] postNotificationName:MsgNPCTalk object:self];
    }
}

- (void)leave
{
    [self stopMusic];
    [[TaskManager sharedInstance] monitorTaskIsDone];
    [_bkView removeFromSuperview];
    [_talkBkView removeFromSuperview];
    [_npcTalkLabel removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:MsgLeavePlace object:nil];
    [[GameManager sharedInstance] gotoStreet];
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIImageView class]]) {
        if (1000 == touch.view.tag) {
            return NO;
        }
    }
    
    return YES;
}
@end
